package youcaihuaoa.weetop.com.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.util.Base64;

import com.robot.base.util.ActivityUtils;
import com.robot.base.util.AppUtils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.RequestBody;

public class BitmapUtils {


    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 60, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.NO_WRAP);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public String bitmapToBase64(Bitmap bitmap, boolean isTest) {
        if (isTest) {
            return getTxtContent(ActivityUtils.getTopActivity(), "test.txt");
        }
        return "";
    }

    /**
     * 读取asset中txt文本内容
     *
     * @param txtName 文件名，带后缀 例： Test.txt
     * @return 读取内容
     */
    public static String getTxtContent(Context context, String txtName) {
        //注册字符输入流读取器
        InputStreamReader isr;
        //注册缓存读取器
        BufferedReader br;
        //读取数据的内容
        String txt = "";

        try {
            //获取assets的管理
            AssetManager am = context.getAssets();
            //打开assets，获取文件字节流
            InputStream is = am.open(txtName);
            //字节流转字符流
            isr = new InputStreamReader(is);
            //字符流存入缓存流读取器中
            br = new BufferedReader(isr);
            //读取txt文件中内容，一行一行进行读取
            while (br.readLine() != null) {
                txt += br.readLine();
            }
            //先打开的后关闭，后打开的先关闭
            //关闭缓存读取器
            br.close();
            //关闭字符流读取器
            isr.close();
            //关闭字节输入流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return txt;
    }
}
